<template>
    <div id="main">
        <div style="height:40px;line-height:40px;background: #f1f1f1;">
            <i class="iconfont icon-close" @click='fnclose()'
                style="font-size: 2rem;color: #404040;padding-left: 17px;cursor:pointer;"></i>
            <div @click='fnEditBlog()'
                style="cursor:pointer;height: 100%;float: right;width: 6rem;text-align: center;color: white;background:linear-gradient(45deg, #9000ff, #5e00ff)">
                发布</div>
            <div @click='fnisTop()' :style="isTop=='开'?'color: white;background: rgb(64, 64, 64);':''"
                style="cursor:pointer;height: 100%;float: right;width: 7rem;text-align: center;color: #474844;background: #dfe0dc; user-select:none;">
                是否置顶({{isTop}})</div>
            <div @click='fnisIndex()' :style="isIndex=='开'?'':'color: #474844;background: #dfe0dc; user-select:none;'"
                style="cursor:pointer;height: 100%;float: right;width: 7rem;text-align: center;color: white;background: rgb(64, 64, 64);">
                首页可见({{isIndex}})</div>
        </div>
        <el-input placeholder="请输入内容" v-model="title">
            <template slot="prepend" style="color: #ff6b6b;">标题</template>
        </el-input>
        <el-input placeholder="请输入图片地址(请在下方编辑器中上传图片,然后会出现图片地址,之后将其复制过来)" v-model="bgImg">
            <template slot="prepend" style="color: #ff6b6b;">封面</template>
        </el-input>
        <div style="height: 40px;position: relative;">
            <span class="upLoad">上传附件</span>
            <el-upload class="upload-demo" :action="uploadUrl" :on-change="handleChange" :file-list="fileList"
                style="opacity: 0;top: 5px;position: absolute;height: 40px;opcity:0;" :on-success='uploadSuccess'
                :on-progress='uploadProgress'>
                <el-button size="small" type="primary">上传附件</el-button>
            </el-upload>
            <span class="progress" :style="'width: calc('+progress+'% - 70px);'"
                v-if='showProgress'>{{Math.floor(progress)}}%</span>
            <span class="upFileUrl">{{upFileUrl}}<i v-if='upFileUrl' class="iconfont icon-close" @click='clearUpfile()'
                    style="cursor:pointer;float: right;height: 40px;line-height: 40px;font-size: 31px;position: absolute;right: 0;"></i>
            </span>
        </div>
        <div style="height: 40px;position: relative;display: flex;">
            <span class="upLoad" style="background-color: rgb(245, 247, 250);cursor: pointer;background: #696969;" @click='fnaddBlogClass()'>增加分类</span>
            <el-select placeholder="请选择博客分类" style="width: 95%;display: inline-block;" v-model="blogClass">
                <el-option :label="blogclass.className" :value="blogclass.className" v-for='blogclass in blogClassList'
                    :key="blogclass.id">
                    <span style="float: left; font-size: 13px">{{blogclass.className}}</span>
                    <span class='iconfont icon-close' style="float:right;color: rgb(255, 255, 255);font-size: 28px;"
                        @click.prevent='fnDelete(blogclass.className)'></span>
                </el-option>
            </el-select>
        </div>

        <div style="height: 90%;overflow: scroll;">
            <mavon-editor :ishljs="true" v-model="markdownValue" style="height: 100%;" ref=md @imgAdd="$imgAdd" />
        </div>
    </div>
</template>


<script>
import { mapGetters, mapActions } from "vuex";
import auth from "../../api/auth";
import blog from "../../api/blog";
import Header from "../../components/Header/Header";
import Footer from "../../components/Footer/Footer";
import { setTimeout } from 'timers';
// import Auth from "../../helpers/loginAnimate.js";
import lottieSave from '../../components/lottie/lottie-save'

export default {
    name: "index",
    components: {
        Header,
        Footer,
        lottieSave
    },
    data() {
        return {
            title: '',
            markdownValue: '',
            blogClass: '',
            blogClassList: [],
            blogUserName: '',
            interval: '',
            bgImg: '',
            attach: '',
            fileList: [],
            uploadUrl: blog.upload(),//请求的地址
            progress: 0,
            showProgress: false,
            upFileUrl: '',//请求成功的地址
            isIndex: '开',
            isTop: '关'
        };
    },
    created() {
        this.findBlogClass()
    },
    mounted() {
        this.getBlog()
    },
    methods: {
        ...mapActions(["login", "checkLogin", "logout", "getPermissions"]),
              fnaddBlogClass(){
            this.$prompt('请输入博客分类', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                   this.addBlogClass(value)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                });       
            });
        },
        async addBlogClass(className){
            try {
                let res = await blog.addBlogClass(className)
                if (res.success) {
                    this.$message.success({ message: '增加成功' })
                    setTimeout(() => {
                        this.findBlogClass()
                    }, 1500)
                } else {
                    this.$message.error({ message: '删除失败' })
                }
            } catch (err) {
                console.log(err)
                this.$message.error({ message: err.errorMsg })
            }
        },
        fnDelete(className) {
            this.$confirm('此操作将删除分类[' + className + '], 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteBlogClass(className)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        async deleteBlogClass(className) {
            try {
                let res = await blog.deleteBlogClass(className)
                if (res.success) {
                    this.$message.success({ message: '删除成功' })
                    setTimeout(() => {
                        this.findBlogClass()
                    }, 1500)
                } else {
                    this.$message.error({ message: '删除失败' })
                }
            } catch (err) {
                console.log(err)
                this.$message.error({ message: err.errorMsg })
            }
        },
        fnisIndex() {
            if (this.isIndex == '开') {
                this.isIndex = '关'
            } else {
                this.isIndex = '开'
            }
        },
        fnisTop() {
            if (this.isTop == '开') {
                this.isTop = '关'
            } else {
                this.isTop = '开'
            }
        },
        clearUpfile() {
            this.upFileUrl = ''
        },
        uploadSuccess(e) {//上传附件
            console.log(e)
            this.showProgress = false

            if (e.success) {
                this.upFileUrl = e.data
            } else {
                this.$message.error('上传失败')
            }
        },
        uploadProgress(e) {
            this.showProgress = true
            this.progress = e.percent
        },
        handleChange(file, fileList) {
        },

        fnclose() {
            window.close();
        },
        checkSame() {
            if (localStorage.getItem('blogSave_edit')) {
                let blogSave2 = JSON.parse(localStorage.getItem('blogSave_edit'))
                console.log(this.title == blogSave2.title, this.title, blogSave2.title)
                if (this.title == blogSave2.title) {
                    console.log('标题相同可以渲染!')
                    this.title = blogSave2.title
                    this.bgImg = blogSave2.bgImg ? blogSave2.bgImg : ''
                    this.blogClass = blogSave2.blogClass
                    this.markdownValue = blogSave2.body
                    this.autoSave()
                } else {
                    console.log('标题不相同不可以渲染!')
                    this.autoSave()
                }
            }
        },
        async getBlog() {
            let res = await blog.findBlogByBlogId(this.$route.query.blogId)
            if (res.success) {
                let date = res.data[0]
                this.markdownValue = date.body
                this.title = date.title
                this.blogClass = date.className
                this.blogUserName = date.userName
                this.upFileUrl = date.upFileUrl
                this.bgImg = date.bgImg
                this.isIndex = date.showIndex == 1 ? '开' : '关'
                this.isTop = date.isTop == 1 ? '开' : '关'
                this.checkSame() //判断自动保存是否一致
            }
            this.autoSave()
        },
        async fnEditBlog() {
            if (this.title == '' || this.markdownValue == '' || this.blogClass == '') return this.$message({ message: '输入内容不可为空', type: 'warning' })
            let isTop = this.isTop == '开' ? 1 : 0
            let isIndex = this.isIndex == '开' ? 1 : 0
            let res = await blog.updateBlog(this.title, this.markdownValue, this.blogClass, this.$route.query.blogId, this.getToday(), this.bgImg, this.upFileUrl, isTop, isIndex)
            console.log(res)
            if (res.success) {
                this.$message({ message: '保存成功', type: 'success' })
                //清空数据
                this.title = ''
                this.markdownValue = ''
                this.blogClass = ''
                this.upFileUrl = ''
                this.bgImg = ''
                localStorage.removeItem('blogSave_edit')
                setTimeout(() => {
                    window.close();
                }, 1000)
            }
        },
        //查找博客分类方法
        async findBlogClass() {
            let res = await blog.findBlogClass()
            if (res.success) {
                this.blogClassList = res.data
            }
        },
        // 绑定@imgAdd event
        $imgAdd(pos, $file) {
            //上传图片接口
            console.log($file)
            var formdata = new FormData();
            formdata.append('file', $file);
            blog.upImg(formdata).then(res => {
                if (res.success) {
                    this.$message({ message: '图片上传成功', type: 'success' })
                    if (!this.bgImg) {
                        this.bgImg = res.data
                    }
                    this.$refs.md.$img2Url(pos, res.data);
                } else {
                    this.$message.error({ message: '上传图片失败' })
                }
            })
        },
        getToday() {
            var data = new Date(),
                year = data.getFullYear(),
                month = ((data.getMonth() + 1)) < 10 ? '0' + (data.getMonth() + 1) : (data.getMonth() + 1),
                day = data.getDate() < 10 ? '0' + data.getDate() : data.getDate(),
                hours = data.getHours() < 10 ? '0' + data.getHours() : data.getHours(),
                minutes = data.getMinutes() < 10 ? '0' + data.getMinutes() : data.getMinutes(),
                seconds = data.getSeconds() < 10 ? '0' + data.getSeconds() : data.getSeconds()
            return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
        },
        autoSave() {
            this.interval = setInterval(() => {
                let blogSave = {}
                blogSave.title = this.title //自动保存标题
                blogSave.blogClass = this.blogClass//自动保存分类
                blogSave.body = this.markdownValue
                blogSave.upFileUrl = this.upFileUrl
                blogSave.bgImg = this.bgImg
                localStorage.setItem('blogSave_edit', JSON.stringify(blogSave))//把用户信息存到localStorage
            }, 10000)
        },
    },
    computed: {
        ...mapGetters(["isLogin", "user"])
    },
};
</script>

<style lang="less" scoped>
@import "../../assets/css/auth.css";
::-webkit-scrollbar-thumb {
    background: white !important;
}
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    background-color: white !important;
}
.upLoad {
    height: 40px;
    display: inline-block;
    background: #696969;
    width: 70px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 13px;
    color: #ffffff;
}
.progress {
    height: 40px;
    display: inline-block;
    width: calc(100% - 70px);
    background: #5252523d;
    position: absolute;
    top: 0;
    margin-left: 70px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.upFileUrl {
    height: 40px;
    display: inline-block;
    width: calc(90% - 70px);
    position: absolute;
    top: 0;
    margin-left: 70px;
    display: flex;
    align-items: center;
    padding-left: 17px;
}
#main {
    height: 100vh;
}
.v-note-op {
    border: 1px solid #e6e6e6 !important;
    box-shadow: none !important;
}
.btn {
    position: fixed;
    top: 87%;
    right: 3%;
    z-index: 9999;
    height: 50px;
    width: 50px;
    background: #f97575;
    border-radius: 50%;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s;
    &:hover {
        background: #ff6262;
        box-shadow: 0 0 6px 1px #ff8888;
        transition: all 0.3s;
    }
}
.markdown-body img {
    max-height: 40rem;
}
</style>

